<template>
  <div class="menuSettings">
    <div class="od-btn">
      <el-button @click="create" icon="el-icon-plus" type="primary"
        >新建</el-button
      >
      <el-button @click="update" icon="el-icon-edit-outline">编辑</el-button>
      <el-button @click="dele" icon="el-icon-delete">删除</el-button>
      <el-select
        v-model="version"
        style="margin-left:10px"
        placeholder="请选择版本"
      >
        <el-option
          v-for="item in editionList"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button
        @click="getPermissionList"
        icon="el-icon-search"
        style="margin-left:10px"
        >查询</el-button
      >
      <el-button @click="postMenu" disabled icon="el-icon-sugar"
        >添加所有菜单</el-button
      >

      <el-input
        placeholder="请输入菜单名称"
        v-model="menuName"
        style="float: right;"
        @keyup.enter.native="search"
      >
        <template slot="append">
          <i class="el-icon-search" @click="search"></i>
        </template>
      </el-input>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
      height="88vh"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"> </el-table-column>
      <el-table-column
        prop="permissionName"
        label="菜单名称"
        width="270"
      ></el-table-column>
      <el-table-column prop="pid" label="上级菜单"></el-table-column>
      <el-table-column prop="type" label="菜单类型"></el-table-column>
      <el-table-column
        prop="permissionCode"
        label="权限编码"
        width="250"
      ></el-table-column>
      <el-table-column
        prop="href"
        label="访问路径"
        width="400"
      ></el-table-column>
      <el-table-column prop="versionType" label="版本类型"></el-table-column>
    </el-table>
    <!-- 点击新建（编辑）菜单的时候弹出的dialog -->
    <div class="mask" v-show="showNew"></div>
    <div class="new_vs" v-show="showNew">
      <div class="vs-top">
        <!-- 新建（编辑）菜单的时候显示对应的字段 -->
        <p>{{ showType }}菜单</p>
        <!-- 右上角的关闭图标 -->
        <i
          class="el-icon-close"
          @click="
            () => {
              this.showNew = false
              this.clearData()
            }
          "
        ></i>
      </div>
      <div class="vs_content">
        <p>菜单名称</p>
        <el-input ref="inp1" v-model="permissionName"></el-input>
        <!-- <p>上级名称</p>
        <el-select v-model="pid">
          <el-option
            v-for="item in pidList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
        <p>版本类型</p>
        <el-select v-model="versionType" @change="versionTypePullSelectChange">
          <el-option
            v-for="item in versionTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <p>上级名称</p>
        <el-select v-model="pid">
          <el-option
            v-for="item in pidList"
            :key="item.id"
            :label="item.permissionName"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <p>菜单类型</p>
        <el-select v-model="type">
          <el-option
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <p>权限编码</p>
        <el-input v-model="permissionCode"></el-input>
        <p>访问路径</p>
        <el-input v-model="href"></el-input>
        <!-- <p>版本类型</p>
        <el-select v-model="versionType" @change="versionTypePullSelectChange">
          <el-option
            v-for="item in versionTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </div>
      <div class="vs-btn">
        <el-button
          @click="
            () => {
              this.showNew = false
              this.clearData()
            }
          "
          >取消</el-button
        >
        <el-button @click="save" type="primary">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
const resources = require('../../../config/tabBar')

import {
  allPermissionList,
  permissionList,
  addPermission,
  updatePermission,
  deletePermission,
  get_diffrent_version_main_meunApi
} from '../../../network/menu'
import enterUp from '../../../components/mixins/enterUp'

export default {
  name: 'menuSettings',
  mixins: [enterUp],
  created() {
    // 一开始的时候，就应该要拿到旗舰版本对应的菜单
    // this.get_diffrent_version_main_meun()
    this.getPermissionList() // 我注释 点击查询触发的函数
    this.inpList = this.getInput()
  },
  data() {
    return {
      // 版本类型下拉框选中的值：菜单 1.旗舰 2. 专业 3. 企业
      versionTypePullSelectValue: 1,
      // 上级名称下拉框选中的值和数组
      // superiorNamePullSelectValue: '',
      superiorNamePullSelectValueList: [],

      editionList: [
        { value: 1, label: '旗舰' },
        { value: 2, label: '专业' },
        { value: 3, label: '企业' }
      ],
      inpList: [],
      showNew: false,
      showType: '',
      menuName: '',
      tableData: [],
      allData: [],
      selected: [],

      version: 1,

      permissionName: '',
      pid: '', // 上级名称 下拉框选中的值
      pidList: [], // 上级名称 下拉框的数组
      type: 0,
      typeList: [
        { value: 0, label: '菜单' },
        { value: 1, label: '权限' }
      ],
      permissionCode: '',
      href: '',
      versionType: 1,
      versionTypeList: [
        { value: 1, label: '旗舰' },
        { value: 2, label: '专业' },
        { value: 3, label: '企业' }
      ],
      updateId: ''
    }
  },
  methods: {
    // 点击新建的时候，也触发了异常，并且默认值为1 （val || 1）
    // 版本类型下拉框的值发生改变的时候，触发的函数
    async versionTypePullSelectChange(val) {
      // val没有值，默认用1
      this.versionTypePullSelectValue = val || 1
      // 根据版本类型获取对应版本的主菜单信息接口
      const { data: res } = await get_diffrent_version_main_meunApi({
        type: this.versionTypePullSelectValue
      })
      // console.log(res)
      if (!res) return this.$message.warning('服务器异常，请稍后再试')
      if (res.code !== 200) return // 不成功直接return
      this.pidList = res.data
    },
    clearData() {
      this.permissionName = ''
      this.pid = ''
      this.type = 0
      this.permissionCode = ''
      this.href = ''
      this.versionType = 1
    },
    // 点击查询按钮的时候，触发的函数
    getPermissionList() {
      // let jxVersionType = document.cookie.match(RegExp('jxVersionType'+'=([^;]+)'))[1]
      // console.log(jxVersionType)
      permissionList({ type: this.version }).then(res => {
        // console.log(res, '签收单')
        // permissionList({type: 3}).then(res => {
        // allData 是后端返回来的数组
        this.allData = res.data.data || []
        this.allData.sort((a, b) => {
          return a.pid - b.pid
        })
        this.allData.forEach(e => {
          if (e.versionType == 1) {
            e.versionType = '旗舰'
          } else if (e.versionType == 2) {
            e.versionType = '专业'
          } else if (e.versionType == 3) {
            e.versionType = '企业'
          }
        })
        // 把获取到的所有菜单，都赋值给表格
        this.tableData = this.allData
        this.pidList = [{ value: 0, label: '基本模块' }]
        for (const e of this.allData) {
          if (e.pid != 0) continue // 就放弃这一个循环，继续下一次循环
          let exist = 0
          for (const i of this.pidList) {
            exist = 0
            if (i.value == e.id) {
              exist = 1
              break
            }
          }
          if (!exist) {
            this.pidList.push({ value: e.id, label: e.permissionName })
          }
        }
      })
    },
    handleSelectionChange(e) {
      this.selected = e
    },
    search() {
      if (!this.menuName) {
        this.tableData = this.allData
      } else {
        this.tableData = []
        for (const i of this.allData) {
          if (i.permissionName.indexOf(this.menuName) != -1) {
            this.tableData.push(i)
          }
        }
      }
    },

    save() {
      if (this.showType == '新建') {
        let d = {
          permissionName: this.permissionName, // 菜单名称
          pid: this.pid || 0, // 上级名称的id
          type: this.type, // 类型(0菜单1权限)
          permissionCode: this.permissionCode,
          href: this.href,
          versionType: this.versionType,
          updateId: this.updateId
        }
        addPermission(JSON.stringify(d)).then(res => {
          console.log(res, '保存接口')
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '新建成功!'
            })
            this.$refs.inp1.focus()
            this.clearData()
            this.getPermissionList()
          } else {
            this.$message.error('新建失败')
          }
        })
      } else {
        let params = {
          id: this.updateId,
          permissionName: this.permissionName,
          pid: this.pid,
          type: this.type,
          permissionCode: this.permissionCode,
          href: this.href,
          versionType: this.versionType,
          updateId: this.updateId
        }
        updatePermission(params).then(res => {
          // console.log(res)
          if (res.data.code == 200) {
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.showNew = false
            this.clearData()
            this.getPermissionList()
          } else {
            this.$message.error('修改失败')
          }
        })
      }
    },
    // 点击新建按钮的时候，触发这个函数
    create() {
      // 点击新建的时候，就要马上获取到对应的菜单
      this.versionTypePullSelectChange()
      this.showNew = true
      this.showType = '新建'
      this.$refs.inp1.focus()
    },
    update() {
      if (!this.selected.length) {
        this.$alert('请选择一条数据再修改', '', {
          confirmButtonText: '确定'
        })
        return
      }
      if (this.selected.length > 1) {
        this.$alert('修改数据不可多选', '', {
          confirmButtonText: '确定'
        })
        return
      }
      this.showNew = true
      this.showType = '编辑'
      this.permissionName = this.selected[0].permissionName
      this.pid = this.selected[0].pid
      this.type = this.selected[0].type
      this.permissionCode = this.selected[0].permissionCode
      this.href = this.selected[0].href
      this.versionType = this.selected[0].versionType
      this.updateId = this.selected[0].id
    },
    dele() {
      let len = this.selected.length
      if (!len) {
        this.$alert('请先选择数据再删除', '', {
          confirmButtonText: '确定'
        })
        return
      }
      let count = 0
      this.selected.forEach(e => {
        deletePermission({ id: e.id }).then(r => {
          count++
        })
      })
      let int = setInterval(() => {
        if (count == len) {
          clearInterval(int)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getPermissionList()
        }
      }, 100)
    },

    postMenu() {
      let that = this
      const menu = resources.menuList
      let i = 0
      let j = 0

      let fidMap = {}
      function postLevel1() {
        const m = menu[i]
        // console.log(m.label)
        menu[i].level2 = menu[i].secondaryMenu
        let d = {
          // 菜单/权限名称
          permissionName: m.label,
          // 父级id
          pid: 0,
          // 类型(0菜单1权限)
          type: 0,
          // 权限编码
          permissionCode: '',
          // 访问路径
          href: '',
          // 版本类型（1旗舰2专业3企业）
          versionType: that.version
        }
        addPermission(JSON.stringify(d)).then(res => {
          if (res.data.code == 200) {
            if (++i == menu.length) {
              i = 0
              permissionList({ type: that.version }).then(r => {
                r.data.data.forEach(e => {
                  if (e.pid === 0) {
                    fidMap[e.permissionName] = e.id
                  }
                })
                postLevel2()
              })
            } else {
              postLevel1()
            }
          }
        })
      }

      function postLevel2() {
        const m = menu[i].level2[j]
        // console.log(i)
        // console.log(j)
        // console.log(m.label)
        let d = {
          // 菜单/权限名称
          permissionName: m.label,
          // 父级id
          pid: fidMap[menu[i].label],
          // 类型(0菜单1权限)
          type: 0,
          // 权限编码
          permissionCode: '',
          // 访问路径
          href: m.path,
          // 版本类型（1旗舰2专业3企业
          versionType: that.version
        }
        addPermission(JSON.stringify(d)).then(res => {
          if (res.data.code == 200) {
            if (++j == menu[i].level2.length) {
              if (++i == menu.length) {
                that.getPermissionList()
                return
              } else {
                j = 0
                postLevel2()
              }
            } else {
              postLevel2()
            }
          }
        })
      }
      postLevel1()
    }
  }
}
</script>
<style scoped>
.menuSettings {
  margin-right: 0.5vw;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}
.od-btn {
  padding: 1.5vh 0;
}
.mask {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  opacity: 0.3;
  z-index: 9;
}
.new_vs {
  position: fixed;
  top: 25%;
  left: 50%;
  transform: translateX(-50%);
  width: 300px;
  height: 375px;
  z-index: 99;
  background-color: white;
}
.new_vs .vs-top {
  height: 40px;
  background-color: #f8f8f8;
}
.new_vs .vs-top p {
  float: left;
  line-height: 40px;
  padding-left: 20px;
  font-weight: bold;
}
.new_vs .vs-top i {
  float: right;
  line-height: 40px;
  padding: 0 16px;
}
.vs-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  margin: 0 20px 20px 0;
}
.vs_content p {
  display: inline-block;
  margin: 0 10px 0 20px;
  line-height: 45px;
}
.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
</style>

<style>
.menuSettings .el-input__icon {
  line-height: 30px;
}
.menuSettings .el-input__inner,
.menuSettings .el-input {
  width: 180px;
  height: 30px;
}
</style>
